package com.tian.service.impl;

import com.tian.common.CommonResult;
import com.tian.dto.ChargeUserLoginResDto;
import com.tian.dto.UserBalanceChangeRespDto;
import com.tian.entity.UserBalanceChangeRecord;
import com.tian.enums.UserBalanceChangeTypeEnum;
import com.tian.mapper.UserBalanceChangeRecordMapper;
import com.tian.service.UserBalanceChangeService;
import com.tian.util.DateUtils;
import com.tian.util.UserCacheUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * {@code @description:} 用户余额变动服务实现类
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-12-07 19:26
 * {@code @version:} 1.0
 */
@Service
public class UserBalanceChangeServiceImpl implements UserBalanceChangeService {

    @Resource
    private UserBalanceChangeRecordMapper userBalanceChangeRecordMapper;

    @Override
    public CommonResult<List<UserBalanceChangeRespDto>> changeList() {
        ChargeUserLoginResDto userInfoCache = UserCacheUtil.getUser();
        Long userId = userInfoCache.getId();
        List<UserBalanceChangeRecord> userBalanceChangeRecords = userBalanceChangeRecordMapper.selectByUserId(userId);
        if (CollectionUtils.isEmpty(userBalanceChangeRecords)) {
            return CommonResult.success();
        }
        List<UserBalanceChangeRespDto> userBalanceChangeRespDtoList = new ArrayList<>();
        userBalanceChangeRecords.forEach(userBalanceChangeRecord -> {
            UserBalanceChangeRespDto userBalanceChangeRespDto = new UserBalanceChangeRespDto();
            userBalanceChangeRespDto.setType(UserBalanceChangeTypeEnum.getDesc(userBalanceChangeRecord.getChangeType()));
            String changeAmount=userBalanceChangeRecord.getChangeType()==UserBalanceChangeTypeEnum.USER_PAY.getType()?
                    "-"+userBalanceChangeRecord.getChangeBalance().toString():userBalanceChangeRecord.getChangeBalance().toString();
            userBalanceChangeRespDto.setChangeAmount(changeAmount+" RMB");
            userBalanceChangeRespDto.setCreateTime(DateUtils.format(userBalanceChangeRecord.getCreateTime(), DateUtils.FORMAT_SECOND));
            userBalanceChangeRespDtoList.add(userBalanceChangeRespDto);
        });
        return CommonResult.success(userBalanceChangeRespDtoList);
    }
}
